package org.jeecg.modules.lab.flair.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.exam.entity.LabExam;
import org.jeecg.modules.lab.exam.exam.service.ILabExamService;
import org.jeecg.modules.lab.flair.entity.LabFlair;
import org.jeecg.modules.lab.flair.service.ILabFlairService;
import org.jeecg.modules.lab.flair.vo.FlairVo;
import org.jeecg.modules.lab.items.entity.LabItems;
import org.jeecg.modules.lab.items.item.service.ILabItemsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
* @Description: 资质考核信息表
* @Author: jeecg-boot
* @Date:   2023-09-04
* @Version: V1.0
*/
@Api(tags="资质考核信息表")
@RestController
@RequestMapping("/flair/labFlair")
@Slf4j
public class LabFlairController extends JeecgController<LabFlair, ILabFlairService> {
   @Autowired
   private ILabFlairService labFlairService;
   @Autowired
   private ILabExamService examService;
   @Autowired
   private ILabItemsService itemsService;
   @Autowired
   private ILabCronJobService labCronJobService;

   /**
    * 分页列表查询
    *
    * @param labFlair
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   //@AutoLog(value = "资质考核信息表-分页列表查询")
   @ApiOperation(value="资质考核信息表-分页列表查询", notes="资质考核信息表-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<FlairVo>> queryPageList(LabFlair labFlair,
                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                     HttpServletRequest req) {
       QueryWrapper<LabFlair> queryWrapper = QueryGenerator.initQueryWrapper(labFlair, req.getParameterMap());
       Page<LabFlair> page = new Page<LabFlair>(pageNo, pageSize);
       IPage<LabFlair> pageList = labFlairService.page(page, queryWrapper);
       List<FlairVo> flairVos = new ArrayList<>();
       pageList.getRecords().forEach(e->{
           FlairVo flairVo = new FlairVo();
           BeanUtils.copyProperties(e,flairVo);

           //考试内容
           if (StringUtils.isNotBlank(e.getExam())) {
               String exam = e.getExam();
               String[] examList = exam.split(",");
               List<String> listName = new ArrayList<>();
               List<LabExam> labExams = new ArrayList<>();
               for (int i = 0; i < examList.length; i++) {
                   //根据id查询考试的名字
                   listName.add( examService.getById(examList[i]).getName());

                   labExams.add(examService.getById(examList[i]));
               }
               String list = String.join(";", listName) ;
               flairVo.setExam(list);
               flairVo.setMyExam(labExams);
           }
           //权限内容
           if (StringUtils.isNotBlank(e.getContent())) {
               String[] split = e.getNode().split(",");
               List<String> listNode = new ArrayList<>(Arrays.asList(split));
               flairVo.setMyNode(listNode);
               String content = e.getContent();
               String[] itemList = content.split(",");
               List<LabItems> labItems = new ArrayList<>();
               for (int i = 0; i < itemList.length; i++) {
                   //根据id查询项目对象
                   labItems.add(itemsService.getById(itemList[i]));
               }
               flairVo.setMyContent(labItems);
           }
           flairVos.add(flairVo);
       });
       Page<FlairVo> myPage = new Page<>(pageNo, pageSize,page.getTotal());
       myPage.setRecords(flairVos);
       return Result.OK(myPage);
   }

   /**
    *   添加
    *
    * @param flairVo
    * @return
    */
   @AutoLog(value = "资质考核信息表-添加")
   @ApiOperation(value="资质考核信息表-添加", notes="资质考核信息表-添加")
//   @RequiresPermissions("flair:lab_flair:add")
   @PostMapping(value = "/add")
   public Result<String> add(@RequestBody FlairVo flairVo) {
       LabFlair labFlair = upDateFlair(flairVo);
       labFlairService.save(labFlair);

       if (MyEnum.sync) {
           long time = new Date().getTime();
           LabCronJob job=new LabCronJob("lab_flair", "0", time, 1);
           labCronJobService.save(job);
       }
       return Result.OK("添加成功！");
   }

    private LabFlair upDateFlair(FlairVo flairVo) {
        LabFlair labFlair = new LabFlair();
        BeanUtils.copyProperties(flairVo,labFlair);

        List<String> listExam = new ArrayList<>();
        if (flairVo.getMyExam()!=null){
            flairVo.getMyExam().forEach(e->{
                listExam.add(e.getId());
            });
            String examString = String.join(",", listExam) ;
            labFlair.setExam(examString);
        }
        List<String> listContent = new ArrayList<>();
        if (!flairVo.getMyContent().isEmpty()){
            labFlair.setNode(String.join(",", flairVo.getMyNode()));
            flairVo.getMyContent().forEach(e->{
                listContent.add(e.getId());
            });
            String contentString = String.join(",", listContent) ;
            labFlair.setContent(contentString);
            labFlair.setSetUp("已设置");
        }else {
            labFlair.setSetUp("未设置");//默认设置成未设置权限
        }
        return labFlair;
    }

    /**
    *  编辑
    *
    * @param flairVo
    * @return
    */
   @AutoLog(value = "资质考核信息表-编辑")
   @ApiOperation(value="资质考核信息表-编辑", notes="资质考核信息表-编辑")
//   @RequiresPermissions("flair:lab_flair:edit")
   @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
   public Result<String> edit(@RequestBody FlairVo flairVo) {
       LabFlair labFlair = upDateFlair(flairVo);
       labFlair.setSynFlag("1");
       labFlairService.updateById(labFlair);

       if (MyEnum.sync) {
           long time = new Date().getTime();
           LabCronJob job=new LabCronJob("lab_flair", "1", time, 1);
           labCronJobService.save(job);
       }
       return Result.OK("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "资质考核信息表-通过id删除")
   @ApiOperation(value="资质考核信息表-通过id删除", notes="资质考核信息表-通过id删除")
//   @RequiresPermissions("flair:lab_flair:delete")
   @DeleteMapping(value = "/delete")
   public Result<String> delete(@RequestParam(name="id",required=true) String id) {
       labFlairService.removeById(id);

       if (MyEnum.sync) {
           long time = new Date().getTime();
           String condition="id='"+id+"'";
           LabCronJob job=new LabCronJob("lab_flair", "2",condition, time, 1);
           labCronJobService.save(job);
       }
       return Result.OK("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "资质考核信息表-批量删除")
   @ApiOperation(value="资质考核信息表-批量删除", notes="资质考核信息表-批量删除")
//   @RequiresPermissions("flair:lab_flair:deleteBatch")
   @DeleteMapping(value = "/deleteBatch")
   public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.labFlairService.removeByIds(Arrays.asList(ids.split(",")));

       if (MyEnum.sync) {
           long time = new Date().getTime();
           String[] split = ids.split(",");
           labCronJobService.saveCronBatch("lab_flair","2",time,split);
       }
       return Result.OK("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "资质考核信息表-通过id查询")
   @ApiOperation(value="资质考核信息表-通过id查询", notes="资质考核信息表-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<LabFlair> queryById(@RequestParam(name="id",required=true) String id) {
       LabFlair labFlair = labFlairService.getById(id);
       if(labFlair==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(labFlair);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param labFlair
   */
//   @RequiresPermissions("flair:lab_flair:exportXls")
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, LabFlair labFlair) {
       return super.exportXls(request, labFlair, LabFlair.class, "资质考核信息表");
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
//   @RequiresPermissions("flair:lab_flair:importExcel")
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, LabFlair.class);
   }

   @GetMapping(value = "/listExam")
    public Result<IPage<LabExam>> listExam(LabExam exam,
                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                           HttpServletRequest req){
       QueryWrapper<LabExam> queryWrapper = QueryGenerator.initQueryWrapper(exam, req.getParameterMap());

       Page<LabExam> page = new Page<LabExam>(pageNo, pageSize);
       IPage<LabExam> pageList = examService.page(page, queryWrapper);
       return Result.OK(pageList);
   }

   @GetMapping(value = "/itemsTree")
    public Result<List<LabItems>> listItems(){
       List<LabItems> list = itemsService.list(new LambdaQueryWrapper<LabItems>().ne(LabItems::getLevel,3));
       return Result.ok(list);
   }
}
